package com.v3webservice.util;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.InputStreamRequestEntity;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

public class WebServiceUtils {

    public static synchronized String accessService(String wsdl, String ns, String method, Map<String, String> params, String result)
            throws Exception
    {
        String soapResponseData = "";
        String param = getParam(params);
        String docType = "GetPPID";
        String inputXml = "{\"BoxId\":\"I190506000167\"}";
        StringBuffer soapRequestData = new StringBuffer("");
        soapRequestData.append("<soapenv:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:urn=\"urn:WebServiceInf-IWebService\">");
        soapRequestData.append("<soapenv:Body>");
        soapRequestData.append("<urn:getIMSData soapenv:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\">");
        soapRequestData.append("<DocType xsi:type=\"xsd:string\">"+docType+"</DocType>");
        soapRequestData.append("<InputDTOXml xsi:type=\"xsd:string\">"+inputXml+"</InputDTOXml>");
        soapRequestData.append("<ResultDTOXml xsi:type=\"xsd:string\">?</ResultDTOXml><ResultMsg xsi:type=\"xsd:string\">?</ResultMsg>");
        soapRequestData.append("</urn:getIMSData>");
        soapRequestData.append("</soapenv:Body></soapenv:Envelope>");
        PostMethod postMethod = new PostMethod(wsdl);

        byte[] b = null;
        InputStream is = null;
        try {
            b = soapRequestData.toString().getBytes("utf-8");
            is = new ByteArrayInputStream(b, 0, b.length);
            RequestEntity re = new InputStreamRequestEntity(is, b.length, "text/xml; charset=UTF-8");
            postMethod.setRequestEntity(re);
            postMethod.setRequestHeader("SOAPAction","urn:WebServiceInf-IWebService#getIMSData");
            HttpClient httpClient = new HttpClient();
            httpClient.setConnectionTimeout(6000000);
            int status = httpClient.executeMethod(postMethod);
            if (status == 200){
                soapResponseData = getMesage(postMethod.getResponseBodyAsString(), result);
            }
        }
        catch (Exception e) {
            e.printStackTrace();
            throw new IllegalArgumentException("common.savefail");
        } finally {
            if (is != null) {
                is.close();
            }
        }
        return soapResponseData;
    }

    public static String getParam(Map<String, String> params)
    {
        String param = "";
        if (params != null) {
            Iterator it = params.keySet().iterator();
            while (it.hasNext()) {
                String str = (String)it.next();
                param = param + "<" + str + ">";
                param = param + (String)params.get(str);
                param = param + "</" + str + ">";
            }
        }
        return param;
    }

    public static String getMesage(String soapAttachment, String result)
    {
        if (result == null) {
            return null;
        }
        soapAttachment = soapAttachment.replaceAll("&lt;", "<");
        soapAttachment = soapAttachment.replaceAll("&gt;", ">");
        return soapAttachment;
    }

    public static String getXmlStr(Map<String, String> params)
    {
        String param = "<root><head><H>";
        if (params != null) {
            Iterator it = params.keySet().iterator();
            while (it.hasNext()) {
                String str = (String)it.next();
                param = param + "<" + str + ">";
                param = param + (String)params.get(str);
                param = param + "</" + str + ">";
            }
        }
        return param + "</H></head></root>";
    }

    public static String getXmlStr(List<Map<String, String>> list)
    {
        String param = "<NewDataSet>";

        if (list != null) {
            for (Map map : list) {
                if (map != null) {
                    param = param + "<NewTable>";
                    Iterator it = map.keySet().iterator();
                    while (it.hasNext()) {
                        String str = (String)it.next();
                        param = param + "<" + str + ">";
                        if (map.get(str) != null) {
                            param = param + String.valueOf(map.get(str));
                        }
                        param = param + "</" + str + ">";
                    }
                    param = param + "</NewTable>";
                }
            }
        }

        param = param + "</NewDataSet>";

        return param;
    }

    public static JSONObject xmlToJson(Element newdataset) throws ParseException {
        JSONObject objJson = new JSONObject();
        Elements returnDm = newdataset.getElementsByTag("return");
        String returnDmXml = returnDm.toString().replace("<return xsi:type=\"xsd:boolean\">","").replace("</return>","").replaceAll(" ","").replaceAll("\n","");
//        System.out.println(returnDmXml);
        if(!"true".equals(returnDmXml)){
            Elements returnMsg = newdataset.getElementsByTag("ResultMsg");
            String msg = returnMsg.toString().replace("<resultmsg xsi:type=\"xsd:string\">","").replace("</resultmsg>","").replaceAll(" ","").replaceAll("\n","");
            System.out.println(msg);
        }
        Elements children = newdataset.getElementsByTag("ResultDTOXml");
//        System.out.println(children.toString());
        String stringxml = children.toString().replace("<resultdtoxml xsi:type=\"xsd:string\">","").replace("</resultdtoxml>","");
//        System.out.println("返回内容字符串为"+stringxml);
//        System.out.println(stringxml.equals("\n ?\n"));
        JSONObject json = JSON.parseObject(stringxml);
//        System.out.println(json.get("AllotId"));
//        System.out.println(json.get("AllotHD"));
//        System.out.println(json.get("MtrlDt"));
//        System.out.println(json.get("RidDt"));
        List<JSONObject> AllotHDList = JSONObject.parseArray(JSONObject.toJSONString(json.get("AllotHD")), JSONObject.class);
        String createDate = AllotHDList.get(0).get("SYS_CRT_DATE").toString();
//        System.out.println("时间为"+createDate);
//        SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
//        Date date = df.parse(createDate);
//        System.out.println(date);
//        System.out.println(AllotHDList.size());
        List<JSONObject> lists = JSONObject.parseArray(JSONObject.toJSONString(json.get("RidDt")), JSONObject.class);
//        List<JSONObject> lists = JSONObject.parseArray(json.get("RidDt"), JSONObject.class);
//        System.out.println(lists.size());
//        String resultCo="B20210109000020,B20210116000017,B20210108000014,B20210111000031,B20210111000027,B20210108000009,B20210110000011,B20210118000017,B20210107000032,B20210120000016";
        for (JSONObject list:lists) {
//            if (resultCo.contains(list.get("RID").toString())){
                System.out.println(list.toJSONString());
//            }
        }
        /*
        for (int i = 0; i < children.size(); i++) {
            Map map = new HashMap();
            Element child = (Element)children.get(i);
            Elements allEls = child.getAllElements();
            for (int j = 1; j < allEls.size(); j++) {
                Element els = (Element)allEls.get(j);
                String nodeName = els.nodeName();
                String value = els.html();

                for (int k = 0; k < nodeName.length(); k++) {
                    if ((nodeName.charAt(k) == '_') && (k < nodeName.length())) {
                        nodeName = nodeName.replace(nodeName.substring(k, k + 2),
                                nodeName.substring(k + 1, k + 2).toUpperCase());
                    }
                }
                map.put(nodeName, value);
            }
            list.add(map);
        }*/
//        objJson.put("data", list);
        return objJson;
    }
}
